<!-- 用户管理 -->
<!-- art-full-height 自动计算出页面剩余高度 -->
<!-- art-table-card 一个符合系统样式的 class，同时自动撑满剩余高度 -->
<!-- 更多 useTable 使用示例请移步至 功能示例 下面的 高级表格示例 -->
<template>
  <div class="art-full-height">
    <!-- 搜索栏 -->
    <CustomSearchBar
      v-model="searchForm"
      :form-items="searchFormList"
      @search="handleSearch"
      @reset="resetSearchParams"
    ></CustomSearchBar>

    <ElCard class="art-table-card" shadow="never">
      <!-- 表格头部 -->
      <ArtTableHeader v-model:columns="columnChecks" :loading="loading" @refresh="refreshData">
        <template #left>
          <ElSpace wrap>
            <ElButton @click="showDialog" v-ripple>新增扩展</ElButton>
          </ElSpace>
        </template>
      </ArtTableHeader>

      <!-- 表格 -->
      <ArtTable
        :loading="loading"
        :data="data"
        :columns="columns"
        :pagination="pagination"
        @pagination:size-change="handleSizeChange"
        @pagination:current-change="handleCurrentChange"
      >
        <template #content="{ row }"><div v-html="row.content"></div></template>
      </ArtTable>
    </ElCard>

    <!-- 表单 -->
    <customForm
      v-model:visible="visiable"
      :title="title"
      :width="800"
      :form-data="formData"
      @submit="getData"
    ></customForm>
  </div>
</template>

<script setup lang="ts">
  import ArtButtonTable from '@/components/core/forms/art-button-table/index.vue'
  import { ElMessageBox, ElMessage, ElTag } from 'element-plus'
  import { useTable } from '@/composables/useTable'
  import { SearchFormItem } from '@/components/core/forms/art-search-bar/index.vue'
  import { systemConfigType, tagType } from '@/maps'
  import {
    CustomFormColumnsType,
    CustomInterfaceFormBody
  } from '@/components/custom/custom-form/it'
  import {
    apiAddSubjectExt,
    apiDeleteSubjectExt,
    apiEditSubjectExt,
    apiGetSubjectExt,
    apiSearchSubjectExt
  } from '@/api/subject'
  import { apiGetSystemConfig } from '@/api/auth'

  // 搜索表单
  const searchForm = ref({
    type: undefined,
    title: undefined
  })

  //搜索提交数据
  const searchData = ref({
    type: '',
    title: ''
  })

  //搜索表单项
  const searchFormList: SearchFormItem[] = [
    {
      label: '类型',
      key: 'type',
      type: 'select',
      props: {
        placeholder: '请选择类型',
        options: [],
        clearable: true
      }
    },
    {
      label: '名称',
      key: 'title',
      type: 'input',
      clearable: true
    }
  ]

  //弹窗展示状态
  const visiable = ref(false)
  //弹窗标题
  const title = ref('')
  //表单数据
  const formData = ref<CustomInterfaceFormBody>({
    columns: [
      {
        type: CustomFormColumnsType.radio,
        title: '类型',
        name: 'type',
        options: [],
        default: 1
      },
      {
        type: CustomFormColumnsType.input,
        title: '名称',
        name: 'title'
      },
      {
        type: CustomFormColumnsType.editor,
        title: '内容',
        name: 'content',
        editorOptions: {
          height: '400px',
          excludeKeys: ['uploadImage', 'uploadVideo']
        }
      }
    ],
    addFun: apiAddSubjectExt,
    getFun: apiGetSubjectExt,
    editFun: apiEditSubjectExt,
    rules: {
      title: [{ required: true, message: '请输入名称', trigger: 'blur' }],
      content: [{ required: true, message: '请输入内容', trigger: 'blur' }]
    }
  })

  const {
    columns,
    columnChecks,
    data,
    loading,
    pagination,
    getData,
    searchParams,
    resetSearchParams,
    handleSizeChange,
    handleCurrentChange,
    refreshData
  } = useTable({
    // 核心配置
    core: {
      apiFn: apiSearchSubjectExt,
      apiParams: {
        current: 1,
        size: 10,
        ...searchForm.value
      },
      columnsFactory: () => [
        { prop: 'id', width: 60, label: 'id', align: 'center' }, // 序号
        {
          prop: 'type',
          label: '类型',
          width: 100,
          align: 'center',
          formatter: (row: any) => {
            return h(ElTag, { type: tagType[row.type] }, () => row.typeName)
          }
        },
        {
          prop: 'title',
          label: '名称'
        },
        {
          prop: 'content',
          label: '内容',
          useSlot: true
        },
        {
          prop: 'addTime',
          label: '创建日期',
          align: 'center',
          width: 180
        },
        {
          prop: 'operation',
          label: '操作',
          width: 120,
          fixed: 'right', // 固定列
          align: 'center',
          formatter: (row: any) =>
            h('div', [
              h(ArtButtonTable, {
                type: 'edit',
                title: '编辑',
                onClick: () => editRecord(row)
              }),
              h(ArtButtonTable, {
                type: 'delete',
                title: '删除',
                onClick: () => deleteRecord(row)
              })
            ])
        }
      ]
    }
  })

  //搜索
  const handleSearch = (params: any) => {
    searchData.value.type = params.type
    searchData.value.title = params.title
    // 搜索参数赋值
    Object.assign(searchParams, searchData.value)
    getData()
  }

  //显示弹窗
  const showDialog = (): void => {
    nextTick(() => {
      title.value = '添加题目扩展'
      formData.value.isEdit = false
      visiable.value = true
    })
  }

  //编辑
  const editRecord = (row: any) => {
    title.value = '编辑题目扩展'
    formData.value.isEdit = true
    formData.value.record = row
    visiable.value = true
  }

  //删除
  const deleteRecord = (row: any) => {
    ElMessageBox.confirm('确定要删除吗？<p>删除后无法恢复，请谨慎操作！</p>', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      dangerouslyUseHTMLString: true
    }).then(() => {
      // console.log('删除')
      apiDeleteSubjectExt({
        id: row.id
      }).then((res) => {
        if (res) {
          ElMessage.success('删除成功')
          getData()
        } else {
          ElMessage.success('删除失败')
        }
      })
    })
  }

  //设置数据
  const setField = () => {
    apiGetSystemConfig(systemConfigType.subjectExt).then((res: any) => {
      const subjectExtValues = Object.values(res)
      searchFormList.forEach((item: any) => {
        if (item.key == 'type') {
          item.props.options = subjectExtValues.map((itemConfig: any) => {
            return {
              label: itemConfig.name,
              value: itemConfig.id
            }
          })
        }
      })

      formData.value.columns?.forEach((item) => {
        if (item.name == 'type') {
          item.options = subjectExtValues.map((itemConfig: any) => {
            return {
              text: itemConfig.name,
              value: itemConfig.id
            }
          })
        }
      })
    })
  }

  onMounted(() => {
    setField()
  })
</script>
